<?php
/**
 * 管理员管理类
 * author: heimuya
 * time: 2014-4-15
 */
 namespace Admin\Controller;
 use Think\Controller;
 
class AdminController extends CommonController {
	
	public function _initialize(){
		parent::_initialize();
	}
	
	function alist(){//administrator list
		$ADMIN = M('Admin');
		$count = $ADMIN->count();
		$Page = new \Think\Page($count, 10);
		$list = $ADMIN->limit($Page->firstRow. ',' . $Page->listRows)->order('id asc')->select();
		$this->empty = "<td colspan='5' class='tb_heade'>暂无数据</td>";
		
		$page = $Page->show();

        $this->assign("page", $page);
		$this->assign('list',$list);

		$this->display();
	}
	
	function addnew(){//add new administrator
		$this->display();
	}
	
	function insert(){//insert new administrator into database
	    $ADMIN = D('Admin');
		if($ADMIN->create()){
			$rs = $ADMIN->add();
			if($rs){
				$this->success('增加成功', U('Admin/alist'));
			}else{
				$this->error('增加失败');
				//echo $Logs->getLastSql();
			}
		}else{
			$this->error($ADMIN->getError());
		}
	}
	
	function edit(){//edit administrator
		$ADMIN = M('Admin');
		$id = is_numeric($_GET['id'])?$_GET['id']:'';
		if($id == ''){
		    $where['id'] = session(C('USER_AUTH_KEY'));
		}else {
			$where['id'] = $id;
		}
		$edit = $ADMIN->where($where)->find();
		$this->assign('edit',$edit);
		$this->display();
	}
	function doedit(){//action for edit administrator
	    $ADMIN = M('Admin');
		$id = I('id');
		$where['id'] = $id;
		$map['username'] = trim(I('username'));
		$map['passwd'] = md5(C('SAFE_CODE').trim(I('opassword')));
		$ifexit = $ADMIN->where($map)->count();
		if($ifexit > 0){
			if(trim($_POST['npassword']) != ''){//新密码不为空
				if(trim($_POST['npassword']) == trim(I('cnpassword'))){//确认密码不为空并且和新密码相等
					$data['pass'] = md5(trim(C('SAFE_CODE').I('npassword')));
				}else{
					$this->error("确认密码不能为空或者和新密码同，请检查");
					exit;
				}
			    //$data['pass'] = md5(trim(C('SAFE_CODE').I('npassword')));
			}
			if(trim(I('telephone')) != ''){
				$data['telephone'] = trim(I('telephone'));
			}
			if(trim(I('email')) != ''){
				$data['email'] = trim(I('email'));
			}

		    if($rs = $ADMIN->where($where)->setField($data)){
				$this->success('修改成功', U('Admin/alist'));
			}else{
				$this->error('修改失败');
			}
		}else {
			$this->error("旧密码不正确，不能完成请求!");
		}
	}
	function deladmin(){
		$id = $_GET['id'];
		if($id != '' && is_numeric($id)){
			if($_SESSION[C('USER_AUTH_KEY')] != $id){
				$where['id'] = $id;
				$rs = M('Admin')->where($where)->delete();
		    	if($rs !== false){
					$this->success('管理员删除成功');
				}else{
					$this->error('管理员删除失败');
				}
			}else {
				$this->error("不能删除自己");
			}
		}else{
			$this->error("参数错误，请稍后再试");
		}
	}
	function shell(){
		echo ACTION_NAME;
		$this->display();
	}
	
}
